"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Plus } from "lucide-react"
import { TicketTemplate } from "@/types/template"
import { columns } from "./columns"
import { DataTable } from "@/components/common/data-table"
import { TemplateDialog } from "@/components/admin/template-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { useAdminStore } from "@/lib/store"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function TemplatesPage() {
  const { templates, deleteTemplate } = useAdminStore()
  
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [selectedTemplate, setSelectedTemplate] = useState<TicketTemplate | undefined>(undefined)

  const handleAddTemplate = () => {
    setSelectedTemplate(undefined)
    setOpenAddEditDialog(true)
  }

  const handleEditTemplate = (template: TicketTemplate) => {
    setSelectedTemplate(template)
    setOpenAddEditDialog(true)
  }

  const handleDeleteClick = (template: TicketTemplate) => {
    setSelectedTemplate(template)
    setOpenDeleteDialog(true)
  }

  const handleConfirmDelete = () => {
    if (selectedTemplate) {
      deleteTemplate(selectedTemplate.id)
      setOpenDeleteDialog(false)
    }
  }
  
  return (
    <div className="space-y-6">
      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-xl font-bold">典型票管理</CardTitle>
          <Button 
            onClick={handleAddTemplate}
            className="rounded-lg bg-primary hover:bg-primary/90"
          >
            <Plus className="mr-2 h-4 w-4" /> 新增模板
          </Button>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">管理标准化的操作票模板，提高开票效率和准确性。</p>
          <DataTable 
            columns={columns({ 
              onEdit: handleEditTemplate, 
              onDelete: handleDeleteClick 
            })} 
            data={templates}
            searchPlaceholder="搜索操作票模板(支持模板名称、票种类型、描述等)"
          />
        </CardContent>
      </Card>

      <TemplateDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        template={selectedTemplate}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除操作票模板"
        description={`确定要删除操作票模板 "${selectedTemplate?.name}" 吗？此操作不可撤销。`}
      />
    </div>
  )
} 